package com.lambkit.web.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lambkit.core.Lambkit;
import com.lambkit.core.http.IController;
import com.lambkit.core.http.ICookie;
import com.lambkit.core.http.IRequest;
import com.lambkit.web.WebConfig;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HutoolShearCaptcha implements ICaptcha {

    protected static String captchaName = "lambkit-captcha-id";

    public void render(IController controller) {
        controller.getResponse().setHeader("Cache-Control", "no-store");
        controller.getResponse().setHeader("Pragma", "no-cache");
        controller.getResponse().setDateHeader("Expires", 0);
        controller.getResponse().setContentType("image/png");
        String captchaKey = IdUtil.simpleUUID();
        controller.setCookie(captchaName, captchaKey, -1, "/");
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(108, 40, 4, 2);
        // 验证码存入session, 180秒过期
        WebConfig webConfig = Lambkit.config(WebConfig.class);
        Lambkit.getCache().put(captchaName, captchaKey, shearCaptcha.getCode(), webConfig.getCaptchaExpireTime());
        // 输出图片流
        try {
            shearCaptcha.write(controller.getResponse().getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public boolean validate(IRequest request, String userInputString) {
        if(StrUtil.isBlank(userInputString)){
            return false;
        }
        // 验证码存入session, 180秒过期
        ICookie cookie = getCookieObject(request, captchaName);
        if(cookie!=null) {
            String captchaKey = cookie.getValue();
            if(StrUtil.isNotBlank(captchaKey)) {
                String shearCaptcha = Lambkit.getCache().get(captchaName, captchaKey);
                Lambkit.getCache().remove(captchaName, captchaKey);
                if(userInputString.equalsIgnoreCase(shearCaptcha)) {
                    return true;
                }
            }
        }
        return false;
    }

    private ICookie getCookieObject(IRequest request, String name) {
        ICookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (ICookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }
}
